package io.jpress.service.provider;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import io.jboot.Jboot;
import io.jboot.aop.annotation.Bean;
import io.jpress.service.ZzRoleService;
import io.jpress.model.ZzRole;
import io.jboot.service.JbootServiceBase;

import java.util.ArrayList;
import java.util.List;

@Bean
public class ZzRoleServiceProvider extends JbootServiceBase<ZzRole> implements ZzRoleService {
    @Override
    public boolean doChangeRoleByIds(Long roleId, Object... ids) {

        for (Object id : ids) {
            //删除role缓存
            Jboot.getCache().remove("user_role", "user_roles:" + id);
        }

        return Db.tx(() -> {

            //清空用户的其他所有角色
            for (Object id : ids) {
                Db.delete("delete from user_zz_role_mapping where user_id = ? ", id);
            }
            System.out.println(roleId);
            System.out.println(ids);
            //添加新的映射
            List<Record> records = new ArrayList<>();
            for (Object id : ids) {
                Record record = new Record();
                record.set("user_id", id);
                record.set("zz_role_id", roleId);
                records.add(record);
            }

            Db.batchSave("user_zz_role_mapping", records, records.size());

            return true;
        });
    }

    @Override
    public String getRoleByUserId(Object user_id) {
        String result= "";
        List<Record> records = Db.find("select * from user_zz_role_mapping where user_id = ?", user_id);

        if (records == null || records.isEmpty()) {
            return null;
        }
        int zz_role_id = records.get(0).getInt("zz_role_id");
        List<Record> temp_records = Db.find("select * from zz_role where id = ?", zz_role_id);
        if (temp_records == null || temp_records.isEmpty()) {
            return null;
        }
        result = temp_records.get(0).getStr("name");
        return result;
    }

    @Override
    public ZzRole getZzRolebyUserID(Object user_id) {
        String result= "";
        List<Record> records = Db.find("select * from user_zz_role_mapping where user_id = ?", user_id);
        if (records == null || records.isEmpty()) {
            return null;
        }
        int zz_role_id = records.get(0).getInt("zz_role_id");
        List<Record> temp_records = Db.find("select * from zz_role where id = ?", zz_role_id);
        if (temp_records == null || temp_records.isEmpty()) {
            return null;
        }
        ZzRole zzRole = new ZzRole();
        return  zzRole.put(temp_records.get(0));
    }


}